package com.chenxi.vhr.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期工具类
 * @author : zhangchenxi
 * @create : 2022-02-11
 **/
public class DateUtil {

    public static String YYYY_FORMAT = "yyyy";

    public static String YYYY_MM_FORMAT = "yyyy-MM";

    public static String YYYY_MM_DD_FORMAT = "yyyy-MM-dd";

    public static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 获取当前Date型日期
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为 yyyy-MM-dd
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD_FORMAT);
    }

    /**
     * 获取当前时间, 默认格式为 yyyy-MM-dd HH:mm:ss
     * @return String
     */
    public static String getTime()
    {
        return dateTimeNow(TIME_FORMAT);
    }

    public static String dateTimeNow(String format)
    {
        return asString(new Date(), format);
    }

    /**
     * 日期转换字符串
     * @param date
     * @param format
     * @return
     */
    public static String asString(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 日期转换字符串
     *   默认格式为 yyyy-MM-dd
     * @param date
     * @return
     */
    public static String asString(Date date) {
        return new SimpleDateFormat(YYYY_MM_DD_FORMAT).format(date);
    }

    /**
     * 字符串转换成日期格式
     * @param in
     * @return
     * @throws ParseException
     */
    public static Date asDate(String in)  throws ParseException {
        return asDate(in, YYYY_MM_DD_FORMAT);
    }

    public static Date asDate(String in, String format) throws ParseException {
        if (StringUtil.isNull(in)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.parse(in);
    }

    /**
     * 日期计算
     * @param d
     * @param i
     * @return
     */
    public static Date addDay(Date d, int i)
    {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.set(5, c.get(5) + i);
        return c.getTime();
    }

    public static Date addMonth(Date d, int i)
    {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.set(2, c.get(2) + i);
        return c.getTime();
    }

    public static Date addHour(Date d, int i)
    {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.set(10, c.get(10) + i);
        return c.getTime();
    }

    public static Date addMinute(Date d, int i)
    {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.set(12, c.get(12) + i);
        return c.getTime();
    }

    public static Date addSecond(Date d, int i)
    {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.set(13, c.get(13) + i);
        return c.getTime();
    }

}
